# agents/client.py
import asyncio
import json
import os
import requests
import telebot
import urllib.parse

# Enter your bot token here
bot = telebot.TeleBot('7293381393:AAGr6J3ADPaci7UaV3C-hj1R4jJGEY_Z8sw')


@bot.message_handler(commands=['start'])
def send_welcome(message):
    # bot.reply_to(message, "Welcome to the chatbot!")
    bot.send_message(message.chat.id, "我是曹大师，请问怎么帮助你?")


@bot.message_handler(func=lambda message: True)
def echo_all(message):
    # bot.reply_to(message, message.text)
    try:
        encoded_message = urllib.parse.quote(message.text)
        response = requests.post('http://127.0.0.1:8000/chat?query=' + encoded_message, timeout=100)
        if response.status_code == 200:
            aisay = json.loads(response.text)
            if "msg" in aisay:
                bot.send_message(message.chat.id, aisay["msg"]["output"].encode("utf-8"))
                audio_path = os.path.join(os.getcwd(), "../voice", f"{aisay['id']}.mp3")
                asyncio.run(check_audio(message, audio_path))
            else:
                bot.send_message(message.chat.id, "Sorry, I couldn't understand that.")
    except requests.RequestException as e:
        bot.send_message(message.chat.id, "Sorry, I couldn't understand that.")
        raise e


# 异步检查语音生成
async def check_audio(message, audio_path):
    while True:
        if os.path.exists(audio_path):
            with open(audio_path, 'rb') as f:
                bot.send_audio(message.chat.id, f)
            os.remove(audio_path)
            break
        else:
            print("please waiting...")
            await asyncio.sleep(1)


# Add more handlers as needed
bot.infinity_polling()
